import { defineStore } from 'pinia'
import { postsAPI } from '../api/posts.js'

export const usePostsStore = defineStore('posts', {
  state: () => {
    return {
      posts: [],
      currentPost: null,
      isLoading: false,
      error: null,
    }
  },
  actions: {
    async getPostById(postId) {
      this.isLoading = true
      this.error = null
      try {
        const response = await postsAPI.getPostById(postId)
        // 增加空值校验
        if (!response) {
          throw new Error('Post data is empty')
        }
        this.currentPost = response
      } catch (error) {
        this.error = error.message
        // 重置数据防止旧数据残留
        this.currentPost = null
        throw error // 抛出错误供组件捕获
      } finally {
        this.isLoading = false
      }
    }
  }
})